import box/{condit,logger,ui} proot/{load,init} shell/termux

shift

# 限制架构范围
case `uname -m` in
  aarch64|armv8a|arm64|armv9*)
    arm=arm64
    ;;
  x86_64|amd64)
    arm=amd64
    ;;
  *)
    Err "不支持或未识别的架构"
    exit
    ;;
esac

  Load-Proot-Config true "$1"
  mkdir -p $PL_HOME

Get-Ask-Ui "确认安装 $RELEASE_NAME ?" yes
case $__return__ in
  yes)
  URL=${mirror}/$RELEASE/${arm}/default
  Info "获取版本信息..."
  UPTIME=$(curl -sL -r2 -t5 $URL | sed -nE 's|.*href="([0-9A-Za-z_%]+)/".*|\1|p' | tail -n1)
  mkdir -p $RELEASE_PATH
  rm rootfs.tar.xz 2>/dev/null

  # 下载
  Msg "下载 rootfs 镜像..."
  if wget -q --show-progress --read-timeout=10 $URL/$UPTIME/rootfs.tar.xz;then
    Msg "下载完成"
  else
    Err "下载失败"
    rm rootfs.tar.xz 2>/dev/null
    rm -rf $RELEASE_PATH
    exit 1
  fi

  # 校验包完整性
  Msg "正校验 rootfs 镜像完整性..."
  if [ -z "$(curl -sL $URL/$UPTIME/SHA256SUMS | grep "$(sha256sum rootfs.tar.xz | awk '{print $1}')")" ];then
    Err "校验不通过，请再次尝试安装容器..."
    rm rootfs.tar.xz 2>/dev/null
    rm -rf $RELEASE_PATH
    exit 1
  fi

  # 安装
  Msg "准备安装 proot 容器..."
  proot --link2symlink tar -xJf rootfs.tar.xz -C $RELEASE_PATH --exclude='dev'||:

  rm $RELEASE_PATH/etc/resolv.conf 2>/dev/null
  echo -e "nameserver 8.8.8.8\nnameserver 8.8.4.4" > $RELEASE_PATH/etc/resolv.conf

  INIT_DIR=$PL_HOME/start
  SH=$INIT_DIR/$RELEASE_NAME.sh
  mkdir -p $INIT_DIR

  # 指定登录 Shell
  for ((i=0;i<${#shell[@]};i++));do
    if [[ ${shell[i]%,*} == default ]];then
      INIT_SHELL=${shell[i]#*,}
      break
    fi
  done  
  for ((i=0;i<${#shell[@]};i++));do
    if [[ ${shell[i]%,*} == $RELEASE_NAME ]];then
      INIT_SHELL=${shell[i]#*,}
      break
    fi
  done

  # 创建启动脚本
  Proot-Write-Init

  # 优化容器 初始化
  RES_SC=$TTB_RES/proot/init/$RELEASE_NAME.sh
  if Has-File $RES_SC;then
    Info "正执行初始配置脚本..."
    source $RES_SC
  fi

  # 优化容器 区域语言（如果有的话）
  LOCALE_CONF=$RELEASE_PATH/etc/locale.conf
  LOCALE_GEN=$RELEASE_PATH/etc/locale.gen
  if Has-File $LOCALE_CONF && Has-File $LOCALE_GEN;then
    Info "正尝试配置区域语言(locale language)"
    if [ -z $(cat $LOCALE_CONF 2>/dev/null | grep zh_CN) ];then      
      sed -i '/zh_CN.UTF-8 UTF-8/s/#//'  $LOCALE_GEN
      sed -i '/en_US.UTF-8 UTF-8/s/#//'  $LOCALE_GEN
      echo 'LANG=zh_CN.UTF-8' > $LOCALE_CONF
      $SH -c locale-gen
      Info "正尝试配置时区(中国上海)"
      cat <<'EOF' | $SH
        shanghai=/usr/share/zoneinfo/Asia/Shanghai
        localtime=/etc/localtime
        if [[ -f $shanghai ]];then
          ln -sf $shanghai $localtime
        fi
EOF
    fi
  fi

  # 优化容器 其他（如果有的话）
  RES_SC=$TTB_RES/proot/releases/$RELEASE_NAME.sh
  if Has-File $RES_SC;then
    Info "正执行后续脚本..."
    cat $RES_SC | $SH
  fi

  # 提示并尝试删除残余
  START_CMD="$TTB_NAME proot/start $RELEASE_NAME"
  Msg "执行 $START_CMD 以启动 $RELEASE_NAME 容器"
  Has-Termux-Plugin api && timeout 0.1 termux-clipboard-set "$START_CMD" 2>/dev/null
  rm rootfs.tar.xz 2>/dev/null
  ;;
no|exit)
  Msg "取消"
  exit
esac